package com.xy.annotaion.handler.config;

import com.xy.annotaion.handler.api.controller.TestController2;
import com.xy.annotaion.handler.importer.TestImportBeanDefinitionRegistrarImpl;
import com.xy.annotaion.handler.importer.TestImportSelectorImpl;
import com.xy.annotaion.handler.interceptor.TestHandlerInterceptor;
import com.xy.annotaion.handler.util.Pointer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Dell
 */
@Configuration
//@TestImportBean
@Import({TestImportBeanDefinitionRegistrarImpl.class, TestImportSelectorImpl.class})
public class TestConfiguration implements WebMvcConfigurer {

    @Bean
    public TestHandlerInterceptor testHandlerInterceptor() {
        return new TestHandlerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(testHandlerInterceptor());
    }

    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
        Pointer.lg("addReturnValueHandlers");
        handlers.add(new HandlerMethodReturnValueHandler() {

            @Override
            public boolean supportsReturnType(MethodParameter returnType) {
                return returnType.getParameterType() == TestController2.Test3A.class;
            }

            @Override
            public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

                Pointer.lg("handleReturnValue");
                Pointer.lg(returnType);
                Pointer.lg(returnValue);
                Pointer.lg(mavContainer);
                Pointer.lg(webRequest);
                //设置被处理了不用接下来不用在处理了
                mavContainer.setRequestHandled(true);
                webRequest.getNativeResponse(HttpServletResponse.class).getWriter().println(returnValue);

            }


        });
    }
}
